package com.peaker.advertisingpro.base

import android.content.Context
import android.os.Looper
import android.os.Process
import android.widget.Toast
import com.peaker.advertisingpro.utils.LogToFile
import java.io.*
import java.lang.Thread.UncaughtExceptionHandler


/**
 *  @ 作者 CODE_LYF
 *  @ 时间   2021/6/13.
 *  代码人生
 */
class CrashHandler private constructor(): UncaughtExceptionHandler {

    private var mContext: Context? = null


    //系统默认的uncatchException
    private var mDefaultException: UncaughtExceptionHandler? = null




    companion object {
        val instance: CrashHandler by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            CrashHandler() }
    }

    /**
     * 初始化
     * @param context
     */
    fun initH(context: Context?) {
        mContext = context
        //系统默认处理类
        mDefaultException = Thread.getDefaultUncaughtExceptionHandler()
        //设置该类为系统默认处理类
        Thread.setDefaultUncaughtExceptionHandler(this)
    }


    override fun uncaughtException(t: Thread?, e: Throwable?) {
        if (!handleExample(e) && mDefaultException != null) { //判断异常是否已经被处理
            mDefaultException!!.uncaughtException(t, e)
        } else {
            try {
                Thread.sleep(3000)
            } catch (e1: InterruptedException) {
                e1.printStackTrace()
            }
            //退出程序
            Process.killProcess(Process.myPid())
            System.exit(1)
        }
    }

    /**
     * 提示用户出现异常
     * 将异常信息保存
     * @param ex
     * @return
     */
    private fun handleExample(ex: Throwable?): Boolean {
        if (ex == null) return false
        Thread {
            Looper.prepare()
            Toast.makeText(mContext, "很抱歉，程序出现异常，即将退出", Toast.LENGTH_SHORT).show()
            Looper.loop()
        }.start()

        //手机设备参数信息

        saveCrashInfoToFile(ex)
        return true
    }



    /**
     * 保存错误信息到文件中
     * @param ex
     */
    private fun saveCrashInfoToFile(ex: Throwable) {
        val writer: Writer = StringWriter()
        val printWriter = PrintWriter(writer)
        ex.printStackTrace(printWriter)
        var exCause = ex.cause
        while (exCause != null) {
            exCause.printStackTrace(printWriter)
            exCause = exCause.cause
        }
        printWriter.close()
        LogToFile.e("全局异常: ",writer.toString())

    }
}